<template>
    <div style="padding: 20px">
    <el-steps style="width: 100%" :active="active" finish-status="success"  simple>
        <el-step title="基本信息" />
        <el-step title="规格参数" />
        <el-step title="销售属性" />
        <el-step title="SKU信息" />
        <el-step title="保存完成" />
    </el-steps>
<div v-show="active===0"><!--基本信息-->
    <el-row>
        <el-col :span="14" :offset="5" style="padding: 30px;margin-top:30px;border: 1px solid #eee;box-shadow: #c8c9cc 5px 5px 15px">
        <el-form ref="dataForm" :rules="rules" :model="form" align="center" label-width="120px">
            <el-form-item label="商品名称" prop="spuName">
                <el-input v-model="form.spuName"/>
            </el-form-item>
            <el-form-item label="商品描述" prop="spuDescription">
                <el-input v-model="form.spuDescription"/>
            </el-form-item>
            <el-form-item label="选择分类" prop="catalogId">
                <CatalogCascader @selectCatalogId="selectCatalogId"/>
            </el-form-item>
            <el-form-item label="选择品牌" prop="brandId">
                <el-select v-model="form.brandId" placeholder="请选择">
                    <el-option v-for="item in brands" :label="item.name" :value=item.brandId />
                </el-select>
            </el-form-item>
            <el-form-item label="商品重量" prop="weight">
                <el-input-number v-model="form.weight" :min="0"/>&nbsp;kg
            </el-form-item>
            <el-form-item label="设置积分" prop="bounds.buyBounds">
                <el-input-number v-model="form.bounds.buyBounds" :min="0"/>
            </el-form-item>
            <el-form-item label="成长值" prop="bounds.growBounds">
                <el-input-number v-model="form.bounds.growBounds" :min="0"/>
            </el-form-item>
            <el-form-item label="商品介绍" prop="decript">
                <UploadImgList type="spu-decript" :limit="1*1" @fileList="fileList"/>
            </el-form-item>
            <el-form-item label="商品图集" prop="images">
                <UploadImgList type="spu-images" @fileList="fileList"/>
            </el-form-item>
            <el-form-item>
                <el-button type="success" activity  @click="nextStep">下一步：设置规格参数</el-button>
            </el-form-item>
        </el-form>
        </el-col>
    </el-row>
 </div>
<div v-show="active===1"><!--规格参数-->
<el-row>
    <el-col :span="16" :offset="4" style="padding: 30px;margin-top:30px;border: 1px solid #eee;box-shadow: #c8c9cc 5px 5px 15px">
        <el-form label-width="100px" style="max-width: 700px">
        <el-tabs tab-position="left" class="demo-tabs scrollThin">
            <el-tab-pane v-for="group in baseAttrGroups" :key="group.attrGroupId" :label="group.attrGroupName">
                    <el-form-item :label="attr.attrName" v-for="attr in group.attrs" label-width="auto">

                        <el-checkbox-group v-if="attr.valueType===1" v-model="attr.attrValues">
                            <el-checkbox :label="value" v-for="value in attr.values">
                                {{value}}
                            </el-checkbox>
                        </el-checkbox-group>

                        <el-radio-group v-if="attr.valueType===0" v-model="attr.attrValues">
                            <el-radio v-for="value in attr.values" :label="value">{{value}}</el-radio>
                        </el-radio-group>
                        <el-checkbox label="快速展示" style="margin-left: 20px;color: #4ab3ff;" v-model="attr.showDesc" />
                    </el-form-item>

            </el-tab-pane>
        </el-tabs>
        </el-form>
        <el-button type="success" activity  @click="preStep">上一步</el-button>
        <el-button type="success" activity  @click="nextStep">下一步</el-button>
    </el-col>
</el-row>
</div>
<div v-show="active===2"><!--销售属性-->
    <el-row>
        <el-col :span="16" :offset="4" style="padding: 30px;margin-top:30px;border: 1px solid #eee;box-shadow: #c8c9cc 5px 5px 15px">
            <el-form label-width="170px" style="max-width: 700px">
                <el-form-item :label="saleAttr.attrName" v-for="(saleAttr,i) in saleAttrs">
                    <el-checkbox-group v-model="saleAttr.attrValues" class="checkboxStyle">
                        <el-checkbox :label="value" v-for="value in saleAttr.values">
                            {{value}}
                        </el-checkbox>
                        <el-input
                                v-if="inputVisible[i]"
                                ref="inputRef"
                                v-model="inputValue"
                                class="w-20"
                                size="small"
                                style="margin-left: 10px;max-width: 100px"
                                @keyup.enter="handleInputConfirm(i)"
                                @blur="handleInputConfirm(i)"
                        />
                        <el-button v-else style="margin-left: 10px" size="small" @click="showInput(i)">
                            + 自定义
                        </el-button>
                    </el-checkbox-group>
                </el-form-item>
            </el-form>
            <el-button type="success" activity  @click="preStep">上一步</el-button>
            <el-button type="success" activity  @click="nextStep">下一步</el-button>
        </el-col>
    </el-row>
</div>
<div v-show="active===3"><!--SKU信息-->
    <div style="margin: 20px;padding: 10px;box-shadow:  #c8c9cc 5px 5px 15px">
    <el-table :data="skus" :border="true" style="width: 100%" row-key="skuName"
              :expand-row-keys="expandRowKeys"
              @expand-change="expandChange"
              header-cell-class-name="headerClass">

        <el-table-column align="center" label="属性组合" prop="attrCombination" >
            <el-table-column align="center" v-for="(item,index) in combinationForTable" :label="item.attrName" :key="item.attrId" >
                <template #default="scope">
                    <span style="margin-left: 10px">{{ scope.row.attrs[index].attrValue}}</span>
                </template>
            </el-table-column>
        </el-table-column>

        <el-table-column align="center" label="商品名称" prop="skuName" >
            <template #default="scope">
                <el-input :title="scope.row.skuName" v-model="scope.row.skuName">
                </el-input>
            </template>
        </el-table-column>

        <el-table-column align="center"  label="标题" prop="skuTitle" >
            <template #default="scope">
            <el-input :title="scope.row.skuTitle" v-model="scope.row.skuTitle"></el-input>
            </template>
        </el-table-column>

        <el-table-column align="center"  label="副标题" prop="skuSubtitle" >
            <template #default="scope">
            <el-input :title="scope.row.skuSubtitle" v-model="scope.row.skuSubtitle"></el-input>
            </template>
        </el-table-column>

        <el-table-column align="center"  label="价格" prop="price" >
            <template #default="scope">
                <el-input-number v-model="scope.row.price" min="0"/>
            </template>
        </el-table-column>

        <el-table-column type="expand">
            <template #default="props">
                <el-row>
                    <el-col :span="3" v-for="(image, index) in props.row.images" class="inputInline" style="margin: 10px">
                        <el-card style="width: 100%">
                            <img :src="image.imgUrl" style="width: 100%" />
                            <div class="inputInline" style="align-items: center;justify-content: center;">
                                <el-tag  style="display: flex;flex-direction: column;align-items: center;margin-top: 5px" >
                                    <el-checkbox v-model="image.checked" style="color: #4ab3ff;"></el-checkbox>
                                <input type="radio" :checked="image.defaultImg==1" @click="setDefaultImg(image, props.row.images, index)" style="color: #4ab3ff;">
                                <label>选为默认</label>
                            </el-tag>
                            </div>
                        </el-card>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="3"  class="inputInline" style="margin: 10px; align-items: center;">
                        <span>选择图集或者</span>
                        <el-upload
                                action = '/api/common/upload/spu-images'
                                :before-upload="beforeUpload"
                                :on-success = onSuccess
                                :show-file-list="false"
                                style="display: flex; justify-content: center"
                        >
                            <span style="color:#4ab3ff" @click="markIndex(props.$index)">上传</span>
                        </el-upload>
                    </el-col>
                </el-row>
                <el-form label-width="auto" style="margin: 10px" >
                    <el-form-item label="设置折扣" class="inputInline">
                        <el-col :span="5" class="inputInline">
                            满&nbsp;<el-input-number v-model="props.row.fullCount" :min="0*1" controls-position="right"/>&nbsp;件
                        </el-col>
                        <el-col :span="5" class="inputInline">
                            打&nbsp;<el-input-number :precision="2" v-model="props.row.discount" :min="0*1" controls-position="right"/>&nbsp;折
                        </el-col>
                        <el-col :span="5" class="inputInline">
                            <el-checkbox v-model="props.row.countStatus" style="margin-left: 20px;color: #4ab3ff;"
                                         value=1 label="可叠加优惠"></el-checkbox>
                        </el-col>
                    </el-form-item>
                    <el-form-item label="设置满减" class="inputInline">
                        <el-col :span="5" class="inputInline">
                            满&nbsp;<el-input-number v-model="props.row.fullPrice" :min="0*1" controls-position="right" />&nbsp;元
                        </el-col>
                        <el-col :span="5" class="inputInline">
                            减&nbsp;<el-input-number v-model="props.row.reducePrice" :min="0*1"  controls-position="right" />&nbsp;元
                        </el-col>
                        <el-col :span="5" class="inputInline">
                            <el-checkbox v-model="props.row.priceStatus" label="可叠加满减" value=1  style="margin-left: 20px;color: #4ab3ff;"></el-checkbox>
                        </el-col>
                    </el-form-item>
                    <el-form-item label="设置会员价" class="inputInline">
                        <el-col :span="5" class="inputInline" v-for="member in props.row.memberPrice" :key="member.id">
                            {{member.name}}&nbsp;<el-input-number :precision="2" :min="0*1" controls-position="right" v-model="member.price" />
                        </el-col>
                    </el-form-item>
                </el-form>
            </template>
        </el-table-column>

    </el-table>
    </div>
    <el-button type="success" activity  @click="preStep">上一步</el-button>
    <el-button type="success" activity  @click="nextStep">下一步</el-button>
</div>
<div v-show="active===4"><!--保存完成-->
    <el-button type="success" activity  @click="preStep">上一步</el-button>
    <el-button type="success" activity  @click="saveSpu">保存</el-button>
</div>
</div>
</template>

<script setup>
    import ModAttrGroup from '@/views/mall/pms/components/ModAttrGroup.vue'
    import ModAttrGroupRelation from '@/views/mall/pms/components/ModAttrGroupRelation.vue'
    import CommonPmsCategory from '@/components/common/CommonPmsCategory.vue'
    import UploadImgList from '@/components/common/UploadImgList.vue'
    import request from '@/utils/request.js'
    import { ElMessage } from 'element-plus'
    import {ref,  reactive, onMounted,nextTick} from 'vue'
    import moment from 'moment'

    import useAuthBtn from '@/hooks/useAuthBtn.js'
    const rules = reactive({
        spuName: [{required: true,message: '请输入商品名称', trigger: 'blur'},],
        spuDescription: [{required: true,message: '请输入商品描述', trigger: 'blur'},],
        catalogId: [{required: true,message: '请选择分类', trigger: 'blur'},],
        brandId: [{required: true,message: '请选择品牌', trigger: 'blur'},],
        weight: [{required: true,message: '请输入商品重量', trigger: 'blur'},],
        "bounds.buyBounds": [{required: true,message: '请输入商品积分', trigger: 'blur'},],
        "bounds.growBounds": [{required: true,message: '请输入商品成长值', trigger: 'blur'},],
        images: [{required: true,message: '请上传商品图集', trigger: 'blur'},],
        decript: [{required: true,message: '请上传商品介绍图', trigger: 'blur'},],
    })
    let options = reactive([])
    let brands = reactive([])
    let baseAttrGroups = reactive([])
    let saleAttrs = reactive([])
    let inputRef = ref([])
    let inputVisible = reactive([])
    let inputValue = ref(null)
    let spus = reactive([])
    let skus = reactive([])
    let combinationForTable = reactive([])
    let loading = ref(true)
    let active = ref(0)
    let dataForm = ref(null)
    let expandRowKeys = reactive([])
    let members = reactive([])
    let skuIndex = ref(-1)
    let form = reactive({
        spuName:"华为（HUAWEI）旗舰手机 Mate 60 Pro+",
        spuDescription:"华为（HUAWEI）旗舰手机 Mate 60 Pro+",
        weight:0.207,
        brandId: 9,
        catalogId: 225,
        baseAttrs:[],
        bounds:{buyBounds:100, growBounds:100},
        images:["http://192.168.31.212/file/spu-images/2658cb6b-a82a-4724-9122-6cc865f05241.jpg",
            "http://192.168.31.212/file/spu-images/08b0f0e5-e195-4bfc-9576-fb2128e4a2b1.jpg",
            "http://192.168.31.212/file/spu-images/e8e24e09-d4a4-4656-8c05-1fab066fa7b0.jpg"],
        decript:["http://192.168.31.212/file/spu-decript/076a6aac-fb11-4861-a282-9f7c7f51f948.jpg"]
    })
    let caprops = {value:"catId", label:"name"}
    let query = reactive({currentPage:1, pageSize:10, total:0, payload: {}})
    onMounted(() => {
        request.get("/api/category/list/tree").then(resp => {
            options.push(...resp)
        });
        let param = {payload:{priviledgeMemberPrice:1}}
        request.post("/api/umsMemberLevel/getUmsMemberLevelPage", param).then(resp => {
            members.push(...resp.records)
        });
    })
    function preStep(){
        active.value--
    }
    function nextStep(){
        if(active.value===0){
            dataForm.value.validate((valid, fields)=>{
                if(valid) {
                    active.value++
                    getAttrGroups()
                }else{
                    ElMessage({message: '缺少必填项！',type: 'error'})
                }
            })
        }else if(active.value===1){
            form.baseAttrs.length=0
            baseAttrGroups.forEach(group=>{// 基本属性赋值到form表单
                if(group.attrs!=null) {
                    group.attrs.forEach(attr => {
                        if (attr.attrValues) {
                            form.baseAttrs.push({
                                attrId: attr.attrId,
                                attrValues: Array.isArray(attr.attrValues) ? attr.attrValues.join(";") : attr.attrValues,
                                showDesc: attr.showDesc ? 1 : 0
                            })
                        }
                    })
                }
            })
            if(form.baseAttrs.length===0){
                ElMessage({message: '未选择基本属性',type: 'error'})
                return
            }
            getSaleAttrs()
            active.value++
        }else if(active.value===2){
            let checkedSaleAttrs = []
            let attrTitles = []
            combinationForTable.length=0
            saleAttrs.forEach(attr =>{
                if(attr.attrValues && attr.attrValues.length > 0){
                    combinationForTable.push({attrId: attr.attrId, attrName: attr.attrName})
                    let attrValueAry = attr.attrValues.map(e=>{
                     return{
                         attrId: attr.attrId,
                         attrName: attr.attrName,
                         attrValue: e
                     }
                    })
                    checkedSaleAttrs.push(attrValueAry)
                }
            })
            skus.length = 0
            doExchange(checkedSaleAttrs, 0);
            active.value++
        }else if(active.value===3){
            form.skus = skus
            active.value++
        }
    }
    let skuSaleAttrs = []
    function doExchange(arr, index){
        for (let i = 0; i<arr[index].length; i++) {

            let tempAttr = arr[index][i]

            skuSaleAttrs[index]={
                attrId: tempAttr.attrId,
                attrName: tempAttr.attrName,
                attrValue: tempAttr.attrValue
            }
            if (index !== arr.length - 1) {
                doExchange(arr, index + 1)
            } else {
                let t = JSON.parse(JSON.stringify(skuSaleAttrs))
                let m = JSON.parse(JSON.stringify(members))
                let imgs = form.images.map(e=>{return {imgUrl:e, defaultImg:0}})
                imgs[0].defaultImg=1 // 第一张默认图片
                let attrTitle = t.map(e=>{
                    return e.attrValue
                }).join(" ")

                skus.push({
                    attrs:t,
                    skuName:form.spuName + attrTitle,
                    skuTitle:form.spuName,
                    price:0,
                    images:imgs,
                    memberPrice:m
                })
            }
        }
    }

    function selectCatalogId(catalogId){
        form.catalogId = catalogId
        request.get(`/api/pmsBrand/getBrandsByCatalogId/${catalogId}`).then(resp => {
            brands.length=0
            brands.push(...resp)
        })
    }
    function getSaleAttrs(){
        let query = {payload:{attrType:0, catalogId: form.catalogId}}// 销售属性
        request.post(`/api/pmsAttr/getPmsAttrPage`,query).then(resp => {
            saleAttrs.length=0
            saleAttrs.push(...resp.records.map(e=>{
                e.values = e.valueSelect.split(";")
                return e
            }))
        })
    }
    function getAttrGroups(){
        request.get(`/api/pmsAttrGroup/getAttrGroupWithAttrByCatalogId/${form.catalogId}`).then(resp => {
            baseAttrGroups.length=0
            baseAttrGroups.push(...resp)
            baseAttrGroups.forEach(group=>{
                if(group.attrs!=null){
                    group.attrs.forEach(attr => {
                        attr.values = attr.valueSelect.split(";")
                    })
                }
            });
        })
    }
    function fileList(type, fileList) {
     if(type==="spu-images"){
         form.images = fileList.map(e=>{return e.url})
     }else if(type==="spu-decript"){
         form.decript = fileList.map(e=>{return e.url})
     }else{
         ElMessage.error('未知图片类型')
     }
     console.log(form)
    }
    const showInput = (index) => {
        inputVisible[index]=true
        nextTick(()=>{
            let temp = inputRef.value
            temp[0].focus()
        })
    }
    const handleInputConfirm = (index)=>{
        let input = inputValue.value
        if(input!==null && input.trim() !== ""){
            saleAttrs[index].values.push(input)
            inputValue.value = null
        }
        inputVisible[index]=false
    }
    function expandChange(row, expandedRows){
        expandRowKeys.length=0
        expandedRows.forEach(r=>{
            expandRowKeys.push(r.skuName)
        })
    }
    function markIndex(index){
        skuIndex.value = index
    }
    const beforeUpload = (rawFile) => {
        console.log("文件格式："+rawFile.type)
        if (rawFile.type !== 'image/jpeg'
            && rawFile.type !== 'image/png'
            && rawFile.type !== 'image/gif'
            && rawFile.type !== 'image/avif') {
            ElMessage.error('必须是 JPG，PNG，gif，avif 格式!')
            return false
        } else if (rawFile.size / 1024 / 1024 > 5) {
            ElMessage.error('文件大小不能大于5MB!')
            return false
        }
        return true
    }

    function onSuccess(response, uploadFile, uploadFiles){
        ElMessage.success('上传成功!')
        skus[skuIndex.value].images.push({imgUrl:response.data, defaultImg:0})
    }

    function saveSpu(){
        form.skus.forEach(e=>{
            if(e.priceStatus){
                e.priceStatus = 1
            }
            if(e.countStatus){
                e.countStatus = 1
            }
            let acturalImgs = null
            if(e.images && e.images.length > 0){
                acturalImgs = []
                e.images.forEach(j=>{
                    let temp = {imgUrl: j.imgUrl, defaultImg: 0}
                    if(j.checked){
                        acturalImgs.push(temp)
                    }
                    if(j.defaultImg){
                        temp.defaultImg = 1
                    }
                })
                e.images = acturalImgs
            }
        })
        request.post(`/api/pmsSpuInfo/save`, form).then(resp => {
            ElMessage.success('保存成功!')
        })
    }

    function setDefaultImg(image, images, index) {
        if (!image.defaultImg){
            for (let i = 0; i <images.length; i++) {
                if(i !== index){
                    images[i].defaultImg = 0
                }else{
                    images[i].defaultImg = 1
                }
            }
        }else{
            image.defaultImg = 0
        }
    }
</script>
<style lang="css" scoped>
    .avatar-uploader .avatar {
        width: 178px;
        height: 178px;
        display: block;
    }
    .avatar-uploader .el-upload {
        border: 1px dashed var(--el-border-color);
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        transition: var(--el-transition-duration-fast);
    }

    .avatar-uploader .el-upload:hover {
        border-color: var(--el-color-primary);
    }

    .el-icon.avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        text-align: center;
    }
    .checkboxStyle{
        display: flex;
        flex-wrap: wrap;
        justify-content: flex-start;
        align-items: center;
    }
    .inputInline {
    display: flex;
    flex-direction: row;
    align-items: flex-start;
    }
    </style>